package com.hiabr.iep.common.web.filter;

import com.alibaba.fastjson.JSONObject;
import com.hiabr.iep.common.domain.constant.CommonConstant;
import com.hiabr.iep.common.domain.context.ThreadLocalContext;
import com.hiabr.iep.common.domain.vo.req.BaseAdminReq;
import com.hiabr.iep.common.domain.vo.req.BaseUserReq;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * @Description AuthFilter
 */
@Slf4j
@WebFilter(urlPatterns = "/*")
public class TraceIdFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String traceId = request.getHeader(CommonConstant.TRACE_ID);
        String userJson = StringUtils.isEmpty(request.getHeader(CommonConstant.USER)) ? null : URLDecoder.decode(request.getHeader(CommonConstant.USER), "UTF-8");
        String adminJson = StringUtils.isEmpty(request.getHeader(CommonConstant.ADMIN)) ? null : URLDecoder.decode(request.getHeader(CommonConstant.ADMIN), "UTF-8");
        if (StringUtils.isNotEmpty(traceId)) {
            MDC.put(CommonConstant.TRACE_ID, traceId);
        } else {
            log.warn("traceId is null");
        }
        if (StringUtils.isNotEmpty(userJson)) {
            //平台用户
            BaseUserReq user = JSONObject.parseObject(userJson, BaseUserReq.class);
            ThreadLocalContext.setUser(user);
        }
        if (StringUtils.isNotEmpty(adminJson)) {
            //管理系统
            BaseAdminReq admin = JSONObject.parseObject(adminJson, BaseAdminReq.class);
            ThreadLocalContext.setAdmin(admin);
        }
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            ThreadLocalContext.remove();
            MDC.clear();
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}
